package SchoolProject.Main.Product;

import SchoolProject.JavaBean.ProductMessage;

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class Product
{
    public static void menu() throws IOException
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("----------列表管理----------");
        System.out.println("---------1 添加产品---------");
        System.out.println("---------2 删除产品---------");
        System.out.println("---------3 更改信息---------");
        System.out.println("---------4 搜索产品---------");
        System.out.println("---------0 退出程序---------");
        System.out.print("请输入你的选择>>>");
        int choice = sc.nextInt();
        switch (choice)
            {
                case 1:
                    addProduct();
                    break;
                case 2:
                    if(deleteProduct())
                    {
                        System.out.println("删除成功");
                    }
                    else
                    {
                        System.out.println("删除失败");
                    }
                    break;
                case 3:
                    updateProduct();
                    break;
                case 4:
                    selectProduct();
                    break;
                case 0:
                    System.out.println("bye");
                    break;
                default:
                    System.out.println("输入错误 请重新输入");
            }
    }

//    public static void main(String[] args) throws IOException
//    {
////            addProduct();
////            deleteProduct();
////        ArrayList<String> IDS =  getAllID();
////        System.out.println(IDS);
//    }
    //核心业务1
    //2025 6 10 李翰哲版权所有

    public static void addProduct() throws IOException
    {

        String ID;
        String name;
        String type;
        int num;
        double price;


        Scanner sc = new Scanner(System.in);

        int count = 0;//计数器 如果多了就提示出错
        do
        {//尝试录入 如果出错 推倒重来
            if(count > 0 )
            {
                System.out.println("ID输入重复 请重新输入");
            }
            System.out.println("请输入产品编号");
            ID = sc.nextLine();
            count++;
        } while (chongfu(ID));//防止ID重复

            System.out.println("请输入产品名称");
            name = sc.nextLine();
            System.out.println("请输入项目规格");
            type = sc.nextLine();
            System.out.println("请输入项目价格");
            price = sc.nextDouble();
            System.out.println("请输入项目数量");
            num = sc.nextInt();



        FileWriter fw = new FileWriter("src\\\\SchoolProject\\\\File\\\\ProductMessage.txt",true);
        fw.write(ID+","+name+","+type+","+price+","+num);
        fw.write("\r\n");
        fw.close();
//        ProductMesssage pm = new ProductMesssage(ID, name, type, price, num);
//        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(""));
//        oos.writeObject(pm);
//        oos.close();  序列化流写不好 换一个简单一点的吧

    }

    //核心业务2
    //2025 6 9 李翰哲版权所有
    public static boolean deleteProduct() throws IOException
    {//返回ture:删除成功
        // false:  删除失败
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要删除的编号");
        String deleteID = sc.nextLine();

        //检查是否存在没有结束的交易信息

        if(containUndone(deleteID))
        {
            return false;
        }

        //读取文件
        FileInputStream fis = new FileInputStream("src\\\\SchoolProject\\\\File\\\\ProductMessage.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        String temp;

        boolean flag = false;//找没找到 默认没找到

        //临时新文件
        File fTemp = new File("src\\\\SchoolProject\\\\File\\\\fTemp.txt");

        while((temp = br.readLine()) != null)
        {
            String[] tempArray = temp.split(",");
//            //测试:遍历字符串
//            for(int i = 0; i < tempArray.length; i++)
//                System.out.println(tempArray[i]);
            ProductMessage pm = new ProductMessage(tempArray[0], tempArray[1], tempArray[2], Double.parseDouble(tempArray[3]), Integer.parseInt(tempArray[4]));

            fTemp.createNewFile();
            if(pm.getProductID().equals(deleteID))
            {
                System.out.println("已找到要删除的编号");
                if(pm.getProductNum()!=0)//库存数量检查
                {
                    System.out.println("库存数量不为0 删除失败");
                    br.close();
                    fTemp.delete();
                    return false;
                }

                flag =  true;
            }
            else{
                //不是要删除的对象 写入新文件
                FileWriter  fw = new FileWriter(fTemp,true);
                fw.write(pm.getProductID()+","+pm.getProductName()+","+pm.getProductType()+","+pm.getProductPrice()+","+pm.getProductNum());
                fw.write("\r\n");
                fw.close();
            }
        }//拿到文件中所有信息
        br.close();

        File f = new File("src\\\\SchoolProject\\\\File\\\\ProductMessage.txt");
        f.delete();
        fTemp.renameTo(new File("src\\\\SchoolProject\\\\File\\\\ProductMessage.txt"));



        return flag;
    }

    // 核心业务3
    //2025 6 9 李翰哲版权所有
    public static void updateProduct() throws IOException {
    Scanner sc = new Scanner(System.in);
    System.out.println("请输入要更改的产品ID");

    ArrayList<String> IDS = getAllID();
    String tempID = sc.nextLine();

    ProductMessage pm = getProductMessageFromId(tempID);
    if (pm == null) {
        System.out.println("没有该编号");
        return;
    }

    // 定义路径常量
    String basePath = "src" + File.separator + "SchoolProject" + File.separator + "File";
    File fTemp = new File(basePath, "fTemp.txt");
    
    int changeID;
    boolean flag = true;
    while (flag) {
        System.out.printf("1 产品编号 = %s\n", pm.getProductID());
        System.out.printf("2 产品名称 = %s\n", pm.getProductName());
        System.out.printf("3 产品类型 = %s\n", pm.getProductType());
        System.out.printf("4 产品价格 = %f\n", pm.getProductPrice());
        System.out.printf("5 剩余数量 = %d\n", pm.getProductNum());
        System.out.println("请输入您要更改的编号");
        System.out.println("输入0退出修改模式");

        if (!sc.hasNextInt()) {
            System.out.println("输入无效，请输入数字");
            sc.next(); // 清除非法输入
            continue;
        }
        changeID = sc.nextInt();
        sc.nextLine(); // 消耗换行符

        switch (changeID) {
            case 0:
                flag = false;
                System.out.println("已退出修改模式");
                break;

            case 1:
                while (true) {
                    System.out.println("请输入要修改成的编号");
                    String newID = sc.nextLine();
                    if (chongfu(newID)) {
                        System.out.println("ID输入重复 请重新输入");
                    } else {
                        pm.setProductID(newID);
                        System.out.println("编号已修改");
                        break;
                    }
                }
                break;

            case 2:
                System.out.println("请输入要修改成的产品名称");
                String name = sc.nextLine();
                pm.setProductName(name);
                System.out.println("产品名称已修改");
                break;

            case 3:
                System.out.println("请输入要修改成的产品类型");
                String type = sc.nextLine();
                pm.setProductType(type);
                System.out.println("产品类型已修改");
                break;

            case 4:
                while (true) {
                    System.out.println("请输入要修改成的产品价格");
                    String priceStr = sc.nextLine();
                    try {
                        double price = Double.parseDouble(priceStr);
                        pm.setProductPrice(price);
                        System.out.println("产品价格已修改");
                        break;
                    } catch (NumberFormatException e) {
                        System.out.println("输入的价格不合法，请重新输入");
                    }
                }
                break;

            case 5:
                while (true) {
                    System.out.println("请输入要修改成的产品数量");
                    String numStr = sc.nextLine();
                    try {
                        int num = Integer.parseInt(numStr);
                        pm.setProductNum(num);
                        System.out.println("产品数量已修改");
                        break;
                    } catch (NumberFormatException e) {
                        System.out.println("输入的数量不合法，请重新输入");
                    }
                }
                break;

            default:
                System.out.println("输入错误 请重新输入");
                break;
        }
    }

    // 如果临时文件存在，先删除
    if (fTemp.exists()) {
        fTemp.delete();
    }
    // 创建新文件
    fTemp.createNewFile();
    // 统一写入新文件
    try (FileWriter fw = new FileWriter(fTemp)) {
        for (String id : IDS) {
            ProductMessage product;
            if (id.equals(tempID)) {
                product = pm;
            } else {
                product = getProductMessageFromId(id);
                if (product == null) {
                    System.out.println("未找到ID: " + id);
                    continue;
                }
            }
            fw.write(String.format("%s,%s,%s,%.2f,%d%n", 
                product.getProductID(),
                product.getProductName(),
                product.getProductType(),
                product.getProductPrice(),
                product.getProductNum()));
        }
        fw.close();
    }

    // 替换原文件
    FileReader  fr = new FileReader("src\\\\SchoolProject\\\\File\\\\fTemp.txt");
    FileWriter fw = new FileWriter("src\\\\SchoolProject\\\\File\\\\ProductMessage.txt");
    BufferedReader br = new BufferedReader(fr);
    while (br.ready()) {
        String line = br.readLine();
        fw.write(line);
        fw.write("\r\n");
    }
    fw.close();
    br.close();
    fr.close();
    fTemp.delete();
}
    public static void updateProduct(ProductMessage pm , int Message , String addOrDelete) throws IOException {
        System.out.println("message = " + Message);

    ArrayList<String> IDS = getAllID();


//    if (pm == null) {
//        System.out.println("没有该编号");
//        return;
//    }

    // 定义路径常量
    String basePath = "src" + File.separator + "SchoolProject" + File.separator + "File";
    File fTemp = new File(basePath, "fTemp.txt");

    //String msgArr[] = Message.split(",");

    String tempID = pm.getProductID();


    // 如果临时文件存在，先删除
    if (fTemp.exists()) {
        fTemp.delete();
    }
    // 创建新文件
    fTemp.createNewFile();
    // 统一写入新文件

    boolean flag;
    try (FileWriter fw = new FileWriter(fTemp)) {
        for (String id : IDS) {
            ProductMessage product;
            //是要修改的ID
            if (id.equals(tempID)) {
                product = pm;
                flag = true;
            } else {
                product = getProductMessageFromId(id);
                if (product == null) {
                    System.out.println("未找到ID: " + id);
                    continue;
                }
                flag = false;
            }
            if (flag) {
                if (addOrDelete.equals("add"))
                {
                    fw.write(String.format("%s,%s,%s,%.2f,%d%n",
                            product.getProductID(),
                            product.getProductName(),
                            product.getProductType(),
                            product.getProductPrice(),
                            product.getProductNum()+Message));
                }
                else if (addOrDelete.equals("delete"))
                {
                    if (product.getProductNum()-Message<0)
                    {
                        System.out.println("error:库存不足!!出库失败!!!!");
                        System.out.println("当前不足的名称为:"+product.getProductName());
                        System.out.println("当前库存为:"+product.getProductNum());
                        return;
                    }
                    fw.write(String.format("%s,%s,%s,%.2f,%d%n",
                            product.getProductID(),
                            product.getProductName(),
                            product.getProductType(),
                            product.getProductPrice(),
                            product.getProductNum()-Message));
                }
            }
            else{
                fw.write(String.format("%s,%s,%s,%.2f,%d%n",
                        product.getProductID(),
                        product.getProductName(),
                        product.getProductType(),
                        product.getProductPrice(),
                        product.getProductNum()));
            }






        }
        fw.close();

    }

    // 替换原文件
    FileReader  fr = new FileReader("src\\\\SchoolProject\\\\File\\\\fTemp.txt");
    FileWriter fw = new FileWriter("src\\\\SchoolProject\\\\File\\\\ProductMessage.txt");
    BufferedReader br = new BufferedReader(fr);
    while (br.ready()) {
        String line = br.readLine();
        fw.write(line);
        fw.write("\r\n");
    }
    fw.close();
    br.close();
    fr.close();
    fTemp.delete();
}



    //核心业务4
    //2025 6 9 李翰哲版权所有
    public static void selectProduct() throws IOException
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要查询的编号");
        String tempID = sc.nextLine();
        ProductMessage pm = getProductMessageFromId(tempID);
        if(pm == null)
            System.out.println("未找到该编号");
        else
            System.out.println("ID"+pm.getProductID()+" 产品名称"+pm.getProductName()+" 产品规格"+pm.getProductType()+" 产品价格"+pm.getProductPrice()+" 剩余数量"+pm.getProductNum());
    }


    //检查是否存在没有结束的交易信息
    private static boolean containUndone(String deleteID) throws IOException
    {
        FileInputStream fis = new FileInputStream("src\\\\SchoolProject\\\\File\\\\InputMessage.txt");
        if(fis.read() != -1)
        {
            System.out.println("存在未处理入站订单 请重新输入要删除的ID");
            fis.close();
            return true;
        }
        fis.close();
        FileInputStream fis2 = new FileInputStream("src\\\\SchoolProject\\\\File\\\\OutputMessage.txt");
        if(fis2.read() != -1)
        {
            System.out.println("存在未处理出站的订单 请重新输入要删除的ID");
            fis2.close();
            return true;
        }
        return false;

    }

    //获取所有ID()为查重提供的辅助方法
    private static ArrayList<String> getAllID() throws IOException
    {

        BufferedReader br = new BufferedReader(new FileReader("src\\\\SchoolProject\\\\File\\\\ProductMessage.txt"));
        ArrayList<String> IDS = new ArrayList<>();
        String temp;
        while((temp = br .readLine()) != null)
        {
            IDS.add(temp.split(",")[0]);
        }

        return IDS;
    }

    //检查ID是否重复
    public static boolean chongfu(String id) throws IOException
    {
        ArrayList<String> IDS =  Product.getAllID();
        if(IDS.contains(id))
        {
            return true;
        }
        return false;

    }

    //辅助方法:通过ID得到整个对象
    public static ProductMessage getProductMessageFromId(String id) throws IOException
    {
        BufferedReader br = new BufferedReader(new FileReader("src\\\\SchoolProject\\\\File\\\\ProductMessage.txt"));
        String temp;
        while((temp = br.readLine()) != null)
        {
            String[] tempArray = temp.split(",");
            if(tempArray[0].equals(id))
            {
                ProductMessage pm = new ProductMessage(tempArray[0], tempArray[1], tempArray[2], Double.parseDouble(tempArray[3]), Integer.parseInt(tempArray[4]));
                return pm;
            }
        }
        //没找到返回null
        return null;
    }

}

